package com.thiswhyme.common.utils.json.gson.typeadapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: Date序列化器
 * @author: thiswhyme
 * @date: 2020/9/17
 */
public class DateSerializerAndDeserializer implements JsonSerializer<Date>, JsonDeserializer<Date> {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private String dateFormat;

    /**
     * 默认构造器
     */
    public DateSerializerAndDeserializer() {
        this(DEFAULT_PATTERN);
    }

    /**
     * 指定格式的构造函数
     * 
     * @param dateFormat
     */
    public DateSerializerAndDeserializer(String dateFormat) {
        super();
        this.dateFormat = dateFormat;
    }

    public String getDateFormat() {
        return this.dateFormat;
    }
    
    private SimpleDateFormat fetchDateFormat() {
        return new SimpleDateFormat(this.dateFormat);
    }

    @Override
    public JsonElement serialize(Date date, Type type, JsonSerializationContext context) {
        String value = null;
        if (date == null) {
            value = "";
        } else {
            value = this.fetchDateFormat().format(date);
        }

        return new JsonPrimitive(value);
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        Date date = new Date();
        if (null != json) {
            try {
                date = this.fetchDateFormat().parse(json.getAsString());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
        return date;
    }
}